import React, {Component} from 'react';
import {connect} from 'dva';
import {
    Button,
    Card,
    Col,
    Form,
    Input,
    message,
    Modal,
    Popconfirm,
    Row,
    Spin,
    Table,
    Tooltip
} from 'antd';
import {PageHeaderWrapper} from "@ant-design/pro-layout";
import {FormattedMessage} from 'umi/locale';
import APP from "@/components/Tool/BaseAPP";

/**
 * 分页参数
 * @Author 肖家添
 * @Date 2019/8/22 15:09
 */
let pagingData = {
    _pageSize: 10,
    _current: 1,
    _total: 0,
};

@connect(({elevatorModel}) => ({
    elevatorModel
}))
@Form.create()
class Elevator extends Component {
    state = {
        loading: false,
        pageDataSource: [],
        selectedKeys: [],
        isShowEditModal: false,
        editData: {},
        hourseId: null,
        isShowElevatorModal: false,
        isModal:false
    };

    componentDidMount() {
        console.log(this.props);
        if (this.props.location) {
            this.findPageDataSource();
        } else {
            const { onRef, parent } = this.props;
            this.parent = parent;
            if (APP.isValidObj(onRef)) {
                onRef(this);
            }
            this.setState({isModal:true});
        }
    }

    openElevatorModal = (hourseId) => {
        const _this = this;
        this.setState({
            hourseId: hourseId,
            isShowElevatorModal: true,
        },function () {
            _this.findPageDataSource();
        });
    };

    findPageDataSource = (e) => {
        let that = this, params = {...pagingData};
        if (e) {
            pagingData._current = 1;
            e.preventDefault();
        }
        if (that.state.hourseId) {
            params.hourseId = that.state.hourseId;
        }
        const {form} = this.props;
        form.validateFieldsAndScroll((err, values) => {
            APP.validNilParams(values);
            params = {...params, ...values};
            requestContinue();
        });

        function requestContinue() {
            const {dispatch} = that.props;
            APP.loading(that);
            dispatch({
                type: "elevatorModel/list",
                payload: params,
                callback: function (data) {
                    APP.closeLoading(that);
                    if (data.success) {
                        const {list, pagination} = data.datas;
                        pagingData._current = pagination.current;
                        pagingData._pageSize = pagination.pageSize;
                        pagingData._total = pagination.total;
                        that.setState({
                            pageDataSource: list,
                            selectedKeys: []
                        });
                    }
                }
            });
        }
    };

    getDataById = () => {
        const {selectedKeys} = this.state;
        if (selectedKeys.length !== 1) return;
        const that = this,
            {dispatch} = that.props,
            id = selectedKeys[0];
        if (!APP.isValidObj(id)) return;
        APP.loading(that);
        dispatch({
            type: "elevatorModel/getElevatorById",
            payload: {id: id},
            callback: function (data) {
                that.setState({
                    loading: false,
                    editData: data.datas,
                    isShowEditModal: true
                });
            }
        });
    };

    enabledControl = (isEnabled) => {
        const { selectedKeys } = this.state;
        if(selectedKeys <= 0) return;
        const that = this, { dispatch } = this.props;
        APP.loading(that);
        dispatch({
            type: "elevatorModel/enabledControl",
            payload: {
                ids: selectedKeys.join(","),
                isEnabled: isEnabled
            },
            callback: function(data){
                APP.closeLoading(that);
                if(data.success){
                    message.success("操作成功");
                    that.findPageDataSource();
                }else{
                    message.error("操作失败！");
                }
            }
        });
    };

    exportData = (type) => {
        const {form} = this.props;
        form.validateFieldsAndScroll((err, values) => {
            APP.validNilParams(values);
            if (this.state.hourseId) {
                values.hourseId = this.state.hourseId;
            }
            APP.exportData({
                parent: this,
                requestUrl: "/api/elevator/exportData",
                fileNamePrefix: "电梯",
                exportType: type,
                tablePagination: pagingData,
                formData:values
            });
        });
    };

    handlerElevatorModal = () => {
        const {form} = this.props;
        form.resetFields();
        let {isShowElevatorModal, hourseId} = this.state;
        isShowElevatorModal = !isShowElevatorModal;
        hourseId = null;
        this.setState({isShowElevatorModal, hourseId});
    };

    render() {
        const {
            loading,
            pageDataSource,
            selectedKeys,
            isShowElevatorModal,
            isModal
        } = this.state;
        const {form} = this.props;
        const that = this;
        const {getFieldDecorator} = form;
        let newColumns = [];
        this.columns.map((item) => {
            if (!(isModal && item.key === 'hourseName')) {
                newColumns.push(item);
            }
        });
        let createBtn = '';
        if (isModal) {
            createBtn = <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => {
                this.setState({isShowEditModal: true});
            }}>
                新增
            </Button>;
        }
        const title = <FormattedMessage id="menu.elevator"/>;
        const card1 =
                <Card style={{marginBottom: 15}}>
                    <Form layout="inline" onSubmit={this.findPageDataSource}>
                        <Row>
                            <Col span={8}>
                                <Form.Item label="所在楼栋">
                                    {getFieldDecorator('sbuild', {})(<Input placeholder="请输入所在楼栋"
                                                                            allowClear={true}/>)}
                                </Form.Item>
                            </Col>
                            <Col span={8}>
                                <Form.Item label="所在单元">
                                    {getFieldDecorator('iunint', {})(<Input placeholder="请输入所在单元"
                                                                            allowClear={true}/>)}
                                </Form.Item>
                            </Col>
                            <Col span={8}>
                                <Form.Item label="电梯名称">
                                    {getFieldDecorator('ename', {})(<Input placeholder="请输入电梯名称"
                                                                           allowClear={true}/>)}
                                </Form.Item>
                            </Col>
                            <Col span={8}>
                                <Form.Item label="电梯品牌">
                                    {getFieldDecorator('brand', {})(<Input placeholder="请输入电梯品牌"
                                                                           allowClear={true}/>)}
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row>
                            <Col style={{textAlign: 'center', height: '32px', lineHeight: '32px', marginTop: 20}}>
                                <Button type="primary" htmlType="submit" {...APP.buttonsStyle_MR15}>
                                    查找
                                </Button>
                                <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => {
                                    this.exportData(1);
                                }}>
                                    导出本页
                                </Button>
                                <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => {
                                    this.exportData(2);
                                }}>
                                    导出所有
                                </Button>
                            </Col>
                        </Row>
                    </Form>
                </Card>;
        const card2 =
            <Card style={{marginBottom: 15}}>
                {createBtn}
                <Tooltip
                    title={selectedKeys.length === 1 ? '' : '请选中一行数据'}
                >
                    <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => {
                        this.getDataById();
                    }}>
                        编辑
                    </Button>
                </Tooltip>
                <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
                    <Popconfirm
                        title="确定删除选中数据吗？"
                        onConfirm={() => {
                            this.enabledControl(-1);
                        }}
                        okText="删除"
                        cancelText="取消"
                        disabled={!(selectedKeys.length > 0)}
                    >
                        <Button type="primary" {...APP.buttonsStyle_MR15}>
                            删除
                        </Button>
                    </Popconfirm>
                </Tooltip>
            </Card>;
        const card3 =
            <Card>
                <Table
                    bordered
                    rowKey={data => `${data.id}`}
                    rowSelection={APP.tableRowSelection(function (selectedRowKeys) {
                        that.setState({selectedKeys: selectedRowKeys});
                    }, selectedKeys)}
                    columns={newColumns}
                    dataSource={pageDataSource}
                    pagination={{
                        pageSize: pagingData._pageSize,
                        current: pagingData._current,
                        total: pagingData._total,
                        onChange: (page) => {
                            pagingData._current = page;
                            this.findPageDataSource();
                        },
                        showTotal: total => `共 ${total} 条数据`,
                    }}
                />
            </Card>;
        let html = [card1,card2,card3,<EditForm parent={this}/>];
        if (isModal) {
            html =
                <Modal
                    visible={isShowElevatorModal}
                    title={title}
                    width={800}
                    confirmLoading={loading}
                    footer={false}
                    onCancel={() => this.handlerElevatorModal()}
                >{html}</Modal>;
        } else {
            html =
                <Spin spinning={loading}>
                    <PageHeaderWrapper title={title}>{html}</PageHeaderWrapper>
                </Spin>
        }
        return (html)
    }

    columns = [{
        title: '楼盘名称',
        dataIndex: 'hourseName',
        key: 'hourseName',
    }, {
        title: '所在楼栋',
        dataIndex: 'sbuild',
        key: 'sbuild',
    }, {
        title: '所在单元',
        dataIndex: 'iunint',
        key: 'iunint',
    }, {
        title: '电梯名称',
        dataIndex: 'ename',
        key: 'ename',
    }, {
        title: '电梯品牌',
        dataIndex: 'brand',
        key: 'brand',
    }, {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
    }, {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
    }, {
        title: '创建人',
        dataIndex: 'creatorName',
        key: 'creatorName',
    }];
}

const EditForm = Form.create()(props => {
    let {parent, form} = props;
    const {dispatch} = parent.props;
    const {loading, isShowEditModal, editData} = parent.state;
    const formItemLayout = {
        style: {
            margin: '0px',
        },
    };
    if (!editData.hourseId && parent.state.hourseId) {
        editData.hourseId = parent.state.hourseId;
    }
    const {getFieldDecorator} = form;

    //-- 显示/隐藏 数据编辑窗口
    function handlerEditModal() {
        form.resetFields();
        let {isShowEditModal, editData} = parent.state;
        isShowEditModal = !isShowEditModal;
        editData = {};
        parent.setState({isShowEditModal, editData});
    }

    const colFloatRight = {
        style: {
            float: 'right'
        },
    };

    function submit() {
        form.validateFields((err, values) => {
            if (err) return;
            APP.validNilParams(values);
            request(values);
        });

        function request(params) {
            APP.loading(parent);
            dispatch({
                type: "elevatorModel/saveElevator",
                payload: params,
                callback: function (data) {
                    APP.closeLoading(parent);
                    if (data.success) {
                        message.success("保存成功！");
                        parent.findPageDataSource();
                        handlerEditModal();
                    } else {
                        message.error(data.msg);
                    }
                }
            });
        }
    }

    return (
        <Modal
            title={<FormattedMessage id="menu.elevator.editElevator"/>}
            visible={isShowEditModal}
            onOk={() => submit()}
            onCancel={() => handlerEditModal()}
            okText="保存"
            cancelText='返回'
            confirmLoading={loading}
        >
            <Form layout="vertical">
                {getFieldDecorator('id', {initialValue: editData.id})(<Input hidden={true}/>)}
                {getFieldDecorator('hourseId', {initialValue: editData.hourseId})(<Input hidden={true}/>)}
                <Row>
                    <Col span={11}>
                        <Form.Item label="所在楼栋" {...formItemLayout}>
                            {getFieldDecorator('sbuild', {
                                initialValue: editData.sbuild,
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入所在楼栋！',
                                    },
                                ],
                            })(<Input placeholder="请输入所在楼栋" allowClear={true}/>)}
                        </Form.Item>
                    </Col>
                    <Col span={11} {...colFloatRight}>
                        <Form.Item label="所在单元" {...formItemLayout}>
                            {getFieldDecorator('iunint', {
                                initialValue: editData.iunint,
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入所在单元！',
                                    },
                                ],
                            })(<Input placeholder="请输入所在单元" allowClear={true}/>)}
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={11}>
                        <Form.Item label="电梯名称" {...formItemLayout}>
                            {getFieldDecorator('ename', {
                                initialValue: editData.ename,
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入电梯名称！',
                                    },
                                ],
                            })(<Input placeholder="请输入电梯名称" allowClear={true}/>)}
                        </Form.Item>
                    </Col>
                    <Col span={11} {...colFloatRight}>
                        <Form.Item label="电梯品牌" {...formItemLayout}>
                            {getFieldDecorator('brand', {
                                initialValue: editData.brand,
                            })(<Input placeholder="请输入电梯品牌" allowClear={true}/>)}
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Form.Item label="备注" {...formItemLayout}>
                        {
                            getFieldDecorator('remark', {
                                initialValue: editData.remark,
                            })(
                                <Input.TextArea
                                    placeholder="请输入备注"
                                    className="custom"
                                    style={{
                                        height: 150,
                                        width: "100%",
                                        resize: 'none'
                                    }}
                                />
                            )
                        }
                    </Form.Item>
                </Row>
            </Form>
        </Modal>);
});

export default Elevator;
